package pl.nazaweb.imedproplus.upload;

import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.xml.sax.SAXException;

/**
 *
 * @author naza
 */
public abstract class UploadServlet extends HttpServlet {

    private int sizeTreshold = 1024;
    private String uploadPath = "/tmp/test/";
    private String repositoryPath = "/tmp";

    abstract void doAfterFileSave(String fileName) throws ParserConfigurationException, SAXException, IOException;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        OutputStream out = response.getOutputStream();
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            ServletFileUpload upload = new ServletFileUpload(this.getDiskFactory());
            try {
                this.saveFileItem(out, upload.parseRequest(httpRequest));
            } catch (FileUploadException ex) {
                this.writeResponse(out, false, "", ex.getMessage());
            }
        } finally {
            out.close();
        }
    }

    private void saveFileItem(OutputStream out, List<FileItem> items)
            throws UnsupportedEncodingException, IOException {
        for (FileItem item : items) {
            if (item.getFieldName().toUpperCase().equals("FILEFIELD")) {
                try {
                    this.saveItemOnDisk(item, out);
                    this.writeResponse(out, true, item.getName(), "");
                } catch (Exception ex) {
                    this.writeResponse(out, false, "", ex.getMessage());
                }
            }
        }
    }

    private DiskFileItemFactory getDiskFactory() {
        DiskFileItemFactory diskFactory = new DiskFileItemFactory();
        if (this.getSizeTreshold() >= 0) {
            diskFactory.setSizeThreshold(this.getSizeTreshold());
        }
        if (this.getRepositoryPath() != null) {
            diskFactory.setRepository(new File(this.getRepositoryPath()));
        }
        return diskFactory;
    }

    private void saveItemOnDisk(FileItem item, OutputStream out)
            throws UnsupportedEncodingException, IOException {
        try {
            item.write(new File("//tmp/test//" + item.getName()));
            this.doAfterFileSave("//tmp/test//" + item.getName());
        } catch (Exception ex) {
            this.writeResponse(out, false, "", ex.getMessage());
            Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void writeResponse(OutputStream out, boolean succes, String file, String message)
            throws UnsupportedEncodingException, IOException {
        String jsonResponse = this.getResponsePojo(succes, file, message);
        out.write(jsonResponse.getBytes("UTF-8"));
    }

    private String getResponsePojo(boolean succes, String file, String message) {
        ResponsePojo response = new ResponsePojo(succes, file, message);
        return new Gson().toJson(response);
    }

    public void setRepositoryPath(String repositoryPath) {
        this.repositoryPath = repositoryPath;
    }

    public int getSizeTreshold() {
        return sizeTreshold;
    }

    public void setSizeTreshold(int sizeTreshold) {
        this.sizeTreshold = sizeTreshold;
    }

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

    public String getRepositoryPath() {
        return repositoryPath;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "upload servlet";
    }
}
